/*
 * @Description: 
 * @Author: Dxcr
 * @Date: 2025-01-15 15:57:20
 * @LastEditTime: 2025-01-16 11:02:29
 * @LastEditors: Dxcr
 */
use serde::{Deserialize,Serialize};
use std::fs;

#[derive(Deserialize)]
pub struct Config {
    pub mqtt_broker: String,
    pub mqtt_port: u16,
    pub mqtt_username: String,
    pub mqtt_password: String,
    pub wellsite_information: WellsiteInformation,
}

impl Config {
    // 从指定路径加载配置文件
    pub fn load(file_path: &str) -> Self {
        match fs::read_to_string(file_path) {
            Ok(config_data) => match serde_json::from_str(&config_data) {
                Ok(config) => config,
                Err(e) => {
                    eprintln!("解析配置文件失败: {}，使用默认配置", e);
                    Self::default() // 返回默认配置
                }
            },
            Err(e) => {
                eprintln!("读取配置文件失败: {}，使用默认配置", e);
                Self::default() // 返回默认配置
            }
        }
    }
}

// 为 Config 实现默认值
impl Default for Config {
    fn default() -> Self {
        Self {
            mqtt_broker: "127.0.0.1".to_string(),
            mqtt_port: 1883,
            mqtt_username: "admin".to_string(),
            mqtt_password: "123456".to_string(),
            wellsite_information: WellsiteInformation {
                well_name: "Default Well".to_string(),
                stage_number: "1".to_string(),
                construction_date: "2025-01-15".to_string(),
            },
        }
    }
}

#[derive(Deserialize, Serialize)]
pub struct WellsiteInformation {
    pub well_name: String,
    pub stage_number: String,
    pub construction_date: String,
}


impl WellsiteInformation {
    /// 将 WellsiteInformation 转换为逗号分隔的字符串，结尾加分号
    pub fn to_csv(&self) -> String {
        format!("{},{},{};", self.well_name, self.stage_number, self.construction_date)
    }
}